import * as express from "express";
import apiSv from "../../services/apiSV";
import * as multer from "multer";
import * as crypto from "crypto";
import * as fs from "fs";
import * as axios from "axios";
import * as path from "path";

let router = express.Router();


function parseStreamData(chunk: string) {
    const lines = chunk.split("\n");
    const dataLines = lines.filter((line) => line.startsWith("data:"));
    const dataObjects = dataLines
      .map((line) => {
        const jsonString = line.replace("data:", "").trim();
        try {
          return JSON.parse(jsonString);
        } catch (error) {
          console.error("Failed to parse JSON:", error);
          return null;
        }
      })
      .filter((data) => data !== null);
  
    return dataObjects[0];
  }
  router.post("/AIbotInfo", async (req, res, next) => {
    try {
      let data = await apiSv(req.api.v4.get, {
        action: "corp.config.get",
        companyID: req.companyId,
        sessionKey: req.t,
        mark: "solutionAgent",
      });
      return res.json({
        status: true,
        data: {
          AgentConfig: data.data.config,
        },
      });
    } catch (e) {
      return next(e);
    }
  });

  router.get("/sendMessage", async (req, res, next) => {
    const { message, FileId, session_id } = req.query;
    const apiKey = "sk-028513aaf9894c49ae20afe23096a0a0";
    const appId = "94752af3d7fd4caeaa434e4be72bc5e3";
    const Url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
    const data: any = {
      input: {
        prompt: message,
      },
      parameters: {
        has_thoughts: "true",
        incremental_output: "true", // 增量输出
        rag_options: {
          session_file_ids: FileId, // 替换为指定的临时文件 ID，多个请用逗号隔开
        },
      },
      debug: {},
    };
    if (session_id !== "null") {
      data.input.session_id = session_id;
    }
    try {
      // 设置响应头，表明这是一个 SSE 响应
      res.setHeader("Content-Type", "text/event-stream");
      res.setHeader("Cache-Control", "no-cache");
      res.setHeader("Connection", "keep-alive");
      res.flushHeaders();
      const response = await axios.default.post(Url, data, {
        headers: {
          Authorization: `Bearer ${apiKey}`,
          "Content-Type": "application/json",
          "X-DashScope-SSE": "enable",
        },
        responseType: "stream",
      });
      response.data.on("data", (chunk: any) => {
        const parsedData = parseStreamData(chunk.toString());
        // parsedData.forEach((dataObj: any) => {
        // 以 SSE 格式发送数据
        res.write(`data: ${JSON.stringify(parsedData)}\n\n`);
        // });
      });
      response.data.on("end", () => {
        console.log("Stream ended");
        res.end();
      });
      response.data.on("error", (error: any) => {
        console.error("Error receiving stream:", error);
        res.end();
      });
    } catch (error) {
      console.error("Error sending request:", error);
      res.status(500).send("Internal Server Error");
    }
  });
  router.post("/updateChat", async (req, res, next) => {
    const { output, sessionID } = req.body;
    try {
      const data = await apiSv(req.api.v4.post, {
        action: "aitools.bailian.updateChat",
        sessionID: sessionID,
        output: output,
      });
      return res.json({
        status: true,
        data: data,
      });
    } catch (err) {
      return next(err);
    }
  });
  router.post("/deleteChat", async (req, res, next) => {
    const { sessionID } = req.body;
    try {
      const data = await apiSv(req.api.v4.post, {
        action: "aitools.bailian.deleteChat",
        sessionID: sessionID,
      });
      return res.json({
        status: true,
        data: data,
      });
    } catch (err) {
      return next(err);
    }
  });
  
  router.post("/addChat", async (req, res, next) => {
    const { deviceID, output, sessionID, title } = req.body;
    try {
      const data = await apiSv(req.api.v4.post, {
        action: "aitools.bailian.addChat",
        deviceID: deviceID,
        sessionID: sessionID,
        title: title,
        output: output,
      });
      return res.json({
        status: true,
        data: data,
      });
    } catch (err) {
      return next(err);
    }
  });
  router.get("/listChat", async (req, res, next) => {
    const { deviceID } = req.query;
    try {
      const data = await apiSv(req.api.v4.get, {
        action: "aitools.bailian.listChat",
        deviceID: deviceID,
      });
      return res.json({
        status: true,
        data: data.data.list || [],
      });
    } catch (err) {
      return next(err);
    }
  });

  export default router;
